package com.zzy.threaddemo;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.RateLimiter;

public class ListenableFutureTest {

	static ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

	public static void main(String[] args) {
		final RateLimiter limiter = RateLimiter.create(1); // 每秒不超过4个任务被提交
		
		for (int i = 0; i < 10; i++) {
			ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
				public Integer call() throws Exception {
					System.out.println("call execute..");
					 TimeUnit.SECONDS.sleep(1);
					 
					 
					// limiter.acquire(); //请求RateLimiter, 超过permits会被阻塞
					if (limiter.tryAcquire()) { // 未请求到limiter则立即返回false
						System.out.println("没有超过" + limiter.getRate());
					} else {
						System.out.println("超过" + limiter.getRate());
					}

					return 7;
				}

			});
			Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
				public void onSuccess(Integer result) {
					System.out.println("get listenable future's result with callback " + result);
				}

				public void onFailure(Throwable t) {
					t.printStackTrace();
				}
			});

		}
		;

	}

}
